﻿using System;
using System.Collections.Generic;
using netaddICTs.Umb.ProtectedMedia.Business.Configuration;

using umbraco.cms.businesslogic;
using umbraco.cms.businesslogic.media;

namespace netaddICTs.Umb.ProtectedMedia.Web.Tree {
   
    public class LoadMedia : umbraco.loadMedia {

        private static readonly Guid protectedUploadGuid = new Guid("6E8C86F8-2CA7-4e11-9AFB-D400C730968C");

        public LoadMedia(string application) : base(application) {}

        public override string GetLinkValue(Media mediaItem, string nodeLink){

            foreach (var property in mediaItem.getProperties) {
                var propertyGuid = property.PropertyType.DataTypeDefinition.DataType.Id;

                if (LinkableMediaDataTypes.Contains(propertyGuid) && !string.IsNullOrEmpty(property.Value.ToString()))
                    return base.GetLinkValue(mediaItem, nodeLink);

                if (string.Compare(protectedUploadGuid.ToString(), propertyGuid.ToString(), true) == 0) {
                    return new System.Text.StringBuilder()
                        .Append(Constants.DownloadURL)
                        .Append("?")
                        .Append(Constants.IdQsKey)
                        .Append("=")
                        .Append(mediaItem.Id.ToString())
                        .Append("&")
                        .Append(Constants.HashCodeQsKey)
                        .Append("=")
                        .Append(Hash(mediaItem.Id))
                        .ToString();
                }
            }
            return string.Empty;
        }

        private static string Hash(int mediaNodeId) {
            return new Business.Encryption.Library().GenerateSHA1(mediaNodeId);
        }

    }
}